package com.foxchen.offline.task.runner;


import com.foxchen.offline.task.TaskHandlerFactory;
import com.foxchen.offline.task.bean.TaskPojo;
import com.foxchen.offline.task.config.OfflineTaskConfig;
import com.foxchen.offline.task.service.OfflineTaskService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class ExportApplicationRunner implements ApplicationRunner {
    @Resource
    private TaskHandlerFactory taskHandlerFactory;
    @Resource
    private OfflineTaskService offlineTaskService;
    @Resource
    private OfflineTaskConfig offlineTaskConfig;
    @Resource
    private RedissonClient redissonClient;

    private static final String TASK_DO_LOCK = "TASK_DO_LOCK";

    @Override
    public void run(ApplicationArguments args) {
        List<TaskPojo> unDoTask = offlineTaskService.selectUnBeginTask();
        log.info("app started,un do task size:{}",unDoTask.size());

        for (TaskPojo taskPojo : unDoTask) {
            RLock clientLock = redissonClient.getLock(TASK_DO_LOCK + offlineTaskConfig.getModuleName() + taskPojo.getId());
            try{
                boolean isGetLock = clientLock.tryLock();
                if (!isGetLock) {
                    log.warn("module:{},task id:{} is running,continue",offlineTaskConfig.getModuleName(),taskPojo.getId());
                    continue;
                }

                try {
                    taskHandlerFactory.executeTask(taskPojo);
                } finally {
                    clientLock.unlock();
                }
            } catch (Exception e){
                Thread.currentThread().interrupt();
                log.error("Interrupted while trying to acquire lock for module:{}, task: {}", offlineTaskConfig.getModuleName(),taskPojo.getId(), e);
            }
        }
    }
}
